<?php

namespace Tools\BloomFilter;

/**
 * Class BloomFilter
 *
 * @package App\Logic\BloomFilter
 */
class BloomFilter
{
    /** @var string $bucket */
    protected $bucket;

    /** @var array $hashFunctionList */
    protected $hashFunctionList;

    /** @var Client $redis */
    protected $client;

    /** @var HashFactory $hashFactory */
    protected $hashFactory;

    /**
     * BloomFilter constructor.
     * @param Client $client
     * @param string $bucket
     * @param array $hashFunctionList
     */
    public function __construct(Client $client, string $bucket, array $hashFunctionList)
    {
        $this->bucket = $bucket;
        $this->hashFunctionList = $hashFunctionList;
        $this->client = $client;

        $this->hashFactory = new HashFactory();
    }

    /**
     * Add.
     *
     * @param string $value
     * @return bool
     */
    public function add(string $value): bool
    {
        return $this->client->add($this->bucket, $this->getOffsetList($value));
    }

    /**
     * Exists.
     *
     * @param string $value
     * @return bool
     */
    public function exists(string $value): bool
    {
        return $this->client->exists($this->bucket, $this->getOffsetList($value));
    }

    /**
     * Get the offset array for $value.
     *
     * @param string $value
     * @return array
     */
    protected function getOffsetList(string $value): array
    {
        $offsetList = [];
        foreach ($this->hashFunctionList as $function) {
            $offsetList[] = $this->hashFactory->$function($value);
        }

        return $offsetList;
    }
}
